package yanyan.com.tochar;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.Image;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.gs.buluo.common.widget.LoadingDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import yanyan.com.tochar.adpter.FullyGridLayoutManager;
import yanyan.com.tochar.adpter.GridImageAdapter;
import yanyan.com.tochar.utils.CoreUtil;
import yanyan.com.tochar.utils.EmptyUtils;
import yanyan.com.tochar.utils.PictureSelectUtil;
import yanyan.com.tochar.utils.ToastUtil;
import zhou.colorpalette.ColorSelectDialog;

/**
 * 图片文字化
 */
public class FunsImgToTextActivity extends Activity {
    private RecyclerView recyclerView;
    private GridImageAdapter adapter;
    private SeekBar propSeekBar;
    private Bitmap newBitmap;
    private ImageView imgRes;
    private EditText editText;
    private TextView colorTx;
    private ColorSelectDialog colorSelectDialog;
    private int backageColor=Color.WHITE;
    private List imgList= new ArrayList<>();//图片集合
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_funs_img_text);
        recyclerView=findViewById(R.id.img_text_recycler);
        propSeekBar=findViewById(R.id.img_text_seekBar);
        imgRes=findViewById(R.id.img_text__res_img);
        editText=findViewById(R.id.img_text_text);
        colorTx=findViewById(R.id.img_text_color);
        //初始化图片选择
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, new GridImageAdapter.onAddPicClickListener() {
            @Override
            public void onAddPicClick() {
                PictureSelectUtil.selectPohto(FunsImgToTextActivity.this,3306);
            }
        });
        adapter.setList(imgList);
        adapter.setSelectMax(1);
        recyclerView.setAdapter(adapter);

        //统计各功能
        CoreUtil.statisticalFuns(this,"funs_img_text");
    }


 public void createTextImg(View view){
     if(imgList!=null && imgList.size()>0){
         LoadingDialog.getInstance().show(FunsImgToTextActivity.this, "正在生成", false);//加载
         Observable.create(new ObservableOnSubscribe<String>() {
             @Override
             public void subscribe(ObservableEmitter<String> e) throws Exception {
                 try{
                     int prop=propSeekBar.getProgress();
                     LocalMedia localMedia= (LocalMedia) imgList.get(0);
                     String path="";
                     if(CoreUtil.isAndroidQ()){
                         path=localMedia.getAndroidQToPath();
                     }else {
                         path= localMedia.getPath();
                     }
                     String text=editText.getText().toString();
                     if(EmptyUtils.isEmpty(text)){
                         text="填充文本";
                     }
                     Bitmap bitmap = PictureSelectUtil.getBitmap(path);
                     int width = bitmap.getWidth();
                     int p=width/2000;
                     if(p>1){
                         bitmap=PictureSelectUtil.getCompressPhoto(path,p);
                     }
                     newBitmap= getTextImg( prop,bitmap,text);
                     runOnUiThread(new Runnable() {
                         @Override
                         public void run() {
                             imgRes.setImageBitmap(newBitmap);
                         }
                     });
                     e.onComplete();
                 }catch (Exception e1){
                     e.onError(e1);
                 }
             }
         }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
             @Override
             public void onSubscribe(Disposable d) {
             }
             @Override
             public void onNext(String s) {

             }
             @Override
             public void onError(Throwable e) {
                 LoadingDialog.getInstance().dismissDialog();
                 ToastUtil.showShotToast(FunsImgToTextActivity.this, "生成失败");
             }
             @Override
             public void onComplete() {
                 LoadingDialog.getInstance().dismissDialog();
                 ToastUtil.showShotToast(FunsImgToTextActivity.this, "生成成功");
             }
         });
     }else {
         ToastUtil.showLongToast(this,"请选择图片");
     }

 }

    /**
     * 颜色选择
     * @param view
     */
 public void selectColor(View view){
     if (colorSelectDialog == null) {
         colorSelectDialog = new ColorSelectDialog(this);
     }
     colorSelectDialog.setOnColorSelectListener(new ColorSelectDialog.OnColorSelectListener() {
         @Override
         public void onSelectFinish(int color) {
             backageColor=color;
             runOnUiThread(new Runnable() {
                 @Override
                 public void run() {
                     colorTx.setBackgroundColor(color);
                 }
             });
         }
     });
     colorSelectDialog.show();
 }


    private Bitmap getTextImg(int prop, Bitmap bitmap,String text){
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        Bitmap resBitmap=Bitmap.createBitmap(width+prop*2,height+prop*2,Bitmap.Config.ARGB_8888);
        Canvas canvas=new Canvas(resBitmap);
        //画颜色的笔
        Paint colorPaint=new Paint();
        colorPaint.setStyle(Paint.Style.FILL);
        colorPaint.setTextAlign(Paint.Align.CENTER);
        colorPaint.setTextSize(prop);
        canvas.drawColor(backageColor);
        for (int y=0;y<height;y+=prop){
            for (int x=0;x<width;x+=prop){
                int pixel = bitmap.getPixel(x, y);
                colorPaint.setColor(pixel);
                String str= String.valueOf(text.charAt((x/prop)%text.length()));
                canvas.drawText(str,x+prop,y+prop,colorPaint);
            }
        }
        return resBitmap;
    }


    /**
     * 图片保存
     * @param view
     */
    public void savenTextImg(View view) {
        if(newBitmap!=null){
            String s = PictureSelectUtil.savePhotoToSD(newBitmap, this);
            ToastUtil.showShotToast(this,"图片已保存至"+s);
        }else {
            ToastUtil.showShotToast(this,"您还没有生成");
        }
    }


    /**
     * 选择图片事件
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            imgList = PictureSelector.obtainMultipleResult(data);
            adapter.setList(imgList);
            adapter.notifyDataSetChanged();
        }
    }

}
